
<script setup lang="ts">
import { ref } from "vue";
import dayjs from 'dayjs';
import { storeToRefs } from "pinia";
import { useTodoListStore } from '@/stores/useTodoListStore'
const todo = ref("");
const todoListStore = useTodoListStore()
const addItemAndClear = (item) => {
  if (item.length === 0) {
    return
  }
  // invokes function in the store:
  todoListStore.addTodo(item, date.value, startTime.value, endTime.value)
  todo.value = ''
}
const date = ref(dayjs().format('YYYY-MM-DD'))
const startTime = ref()
const onStartTimeChange = (e) => {
  startTime.value = e.detail.value
}
// console.log('todoListStore', todoListStore)
const { todoList } = storeToRefs(todoListStore);
const endTime = ref()
const onEndTimeChange = (e) => {
  endTime.value = e.detail.value
}
</script>

<template>
  <form @submit.prevent="addItemAndClear(todo)">
    <view class="flex flex-col items-center justify-center m4 gap-2">
      <view class="flex items-center w-full">
        <uni-datetime-picker
          v-model="date"
          type="date"
          class="flex-1"
        />
        <view class="flex-1 flex gap-2">
          <picker mode="time" @change="onStartTimeChange">
            {{ startTime ?? '开始时间' }}
          </picker>
          至
          <picker mode="time" @change="onEndTimeChange">
            {{ endTime ?? '结束时间' }}
          </picker>
        </view>
      </view>
      <!-- -->
      <div class="flex items-center justify-center w-full">
        <input placeholder="请输入" v-model="todo" type="text" class="flex-1" @keyup.enter="addItemAndClear(todo)" />
        <button @click="addItemAndClear(todo)">新建</button>
      </div>
    </view>
  </form>
  <view v-for="(todo, todoIndex) in todoList" :key="todo.id" class="m4">
    <view v-if="todo.date !== (todoList[todoIndex - 1] && todoList[todoIndex - 1].date)" class="font-600">
      {{ todo.date }}
    </view>
    <view class="flex items-center justify-center">
      <view :class="{ completed: todo.completed }">
        <text v-if="todo.startTime || todo.endTime" class="c-hex-666">
          {{ todo.startTime }}至{{ todo.endTime }}
        </text>
        {{ todo.item }}
      </view>
      <text @click.stop="todoListStore.toggleCompleted(todo.id)" class="ml-a p2">&#10004;</text>
      <text @click="todoListStore.deleteTodo(todo.id)" class="p2">&#10060;</text>
    </view>
  </view>
</template>

<style>
.completed {
  text-decoration: line-through;
}
.flex {
  display: flex;
}
.flex-col {
  flex-direction: column;
}
.flex-1 {
  flex: 1;
}
.w-full {
  width: 100%;
}
.m4 {
  margin: 16rpx;
}
.p2 {
  padding: 8rpx;
}
.items-center {
  align-items: center;
}
.justify-center {
  justify-content: center;
}
.ml-a {
  margin-left: auto;
}
.gap-2 {
  gap: 8rpx;
}
.font-600 {
  font-weight: 600;
}
.c-hex-666 {
  color: #666;
}
</style>